package com.example.baselibs.utils.ImgUtils;

import android.content.Context;
import android.graphics.Bitmap;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.request.FutureTarget;
import com.bumptech.glide.request.RequestOptions;
import com.example.baselibs.R;

import java.util.concurrent.ExecutionException;

public class GlideManager {
    private static GlideManager instance;

    public GlideManager() {
    }

    public static GlideManager getInstance(){
        if (instance==null){
            synchronized (GlideManager.class){
                if (instance==null){
                    instance=new GlideManager();
                }
            }
        }
        return instance;
    }
    /**
     * 加载圆形头像，
     * 加载失败，加载中统一提供默认的头像
     */
    public void loadRoundAvatar(Object url, ImageView iv){
        getGilde(iv.getContext()).applyDefaultRequestOptions(new RequestOptions()
                    .circleCrop()
                    .error(R.drawable.ic_longma_logo))
                .load(url)
                .into(iv);
    }

    /**
     * 加载普通图片
     * @param url
     * @param iv
     */
    public void loadImage(Object url,ImageView iv){
        getGilde(iv.getContext()).load(url).into(iv);
    }

    /**
     * 获得Glide，RequestManager的实例
     * @return
     */
    private RequestManager getGilde(Context context){
        return Glide.with(context);
    }

    /**
     * 利用Glide获取Bitmap。此方法需要在后台线程上调用
     * 需要开一条独立的子线程使用，需要改进
     * @param url
     * @param <T>
     * @return
     */
    public <T> Bitmap getBitmap(Context context,T url){
        Bitmap bitmap = null;
        FutureTarget<Bitmap> bitmapFutureTarget=Glide.with(context).asBitmap().load(url).submit();
        try {
            bitmap=bitmapFutureTarget.get();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

}
